<template>
	<view class="login-time-container">
		<view class="header">
			<text class="title"></text>
		</view>

		<view class="time-picker">
			<view class="picker-item">
				<text class="item-label">开始时间</text>
				<picker mode="time" :value="displayStartTime" @change="onStartTimeChange">
					<view class="picker-value">{{ displayStartTime }}</view>
				</picker>
			</view>

			<view class="picker-item">
				<text class="item-label">结束时间</text>
				<picker mode="time" :value="displayEndTime" @change="onEndTimeChange">
					<view class="picker-value">{{ displayEndTime }}</view>
				</picker>
			</view>
		</view>

		<view class="time-range-tip">
			<text>当前设置的登录时间段：</text>
			<text class="time-range">{{ displayStartTime }} - {{ displayEndTime }}</text>
		</view>

		<view class="time-validation" v-if="!isValidTimeRange">
			<text class="warning-icon">⚠️</text>
			<text class="warning-text">结束时间必须晚于开始时间</text>
		</view>

		<button class="save-btn" @click="saveLoginTime" :disabled="!isValidTimeRange">
			保存设置
		</button>

		<view class="current-status">
			<text class="status-label">当前登录状态：</text>
			<text class="status-value" :class="isLoginAllowed ? 'allowed' : 'blocked'">
				{{ isLoginAllowed ? '允许登录' : '禁止登录' }}
			</text>
		</view>
	</view>
</template>

<script>
	import {
		request
	} from '@/utils/request.js'
	export default {
		data() {
			return {
				star_time: '00:00:00', // 原始格式（带秒）
				end_time: '00:00:00', // 原始格式（带秒）
				displayStartTime: '00:00', // 显示格式（分）
				displayEndTime: '00:00', // 显示格式（分）
				isValidTimeRange: false,
				isLoginAllowed: false,
				nextChangeTime: '',
				timer: null,
				aaaa: 1111,
			}
		},
		watch: {
			// 监听显示时间变化，更新原始时间
			displayStartTime(newVal) {
				this.star_time = `${newVal}:00` // 添加秒部分
				this.validateTimeRange()
			},
			displayEndTime(newVal) {
				this.end_time = `${newVal}:00` // 添加秒部分
				this.validateTimeRange()
			}
		},
		onLoad() {
			this.getDefultTime()
			this.updateDisplayTimes()
			this.checkLoginStatus()
			// this.startStatusCheckTimer()
		},
		onUnload() {
			// 页面卸载时清除定时器
			if (this.timer) {
				clearInterval(this.timer)
			}
		},
		methods: {
			async getDefultTime() {
				try {
					// 模拟API请求
					const res = await request({
						url: 'index/time-info',
						method: 'get',
					})
					console.log(res)
					if (res.status == 200) {
						this.star_time = res.data.star_time;
						this.end_time = res.data.end_time;
						this.updateDisplayTimes()
						
					}
				} catch (error) {
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				} finally {}
			},
			// 开始时间变更
			onStartTimeChange(e) {
				this.displayStartTime = e.detail.value
			},

			// 结束时间变更
			onEndTimeChange(e) {
				this.displayEndTime = e.detail.value
			},

			// 更新显示时间
			updateDisplayTimes() {
				this.displayStartTime = this.star_time.substring(0, 5)
				this.displayEndTime = this.end_time.substring(0, 5)
				this.validateTimeRange()
			},

			// 验证时间范围
			validateTimeRange() {
				const startParts = this.star_time.split(':')
				const endParts = this.end_time.split(':')

				const start = new Date()
				const end = new Date()

				start.setHours(parseInt(startParts[0]), parseInt(startParts[1]), parseInt(startParts[2]))
				end.setHours(parseInt(endParts[0]), parseInt(endParts[1]), parseInt(endParts[2]))

				// 如果开始时间晚于结束时间，认为是跨天的时间段
				this.isValidTimeRange = start < end ||
					(start.getHours() === end.getHours() && start.getMinutes() === end.getMinutes() && start.getSeconds() <
						end.getSeconds())
			},

			// 检查当前是否允许登录
			checkLoginStatus() {
				const now = new Date()
				const currentHours = now.getHours()
				const currentMinutes = now.getMinutes()
				const currentSeconds = now.getSeconds()

				const [startHours, startMinutes, startSeconds] = this.star_time.split(':').map(Number)
				const [endHours, endMinutes, endSeconds] = this.end_time.split(':').map(Number)

				// 创建当前时间、开始时间和结束时间的Date对象
				const currentTime = new Date()
				currentTime.setHours(currentHours, currentMinutes, currentSeconds)

				const startTime = new Date()
				startTime.setHours(startHours, startMinutes, startSeconds)

				const endTime = new Date()
				endTime.setHours(endHours, endMinutes, endSeconds)

				// 判断当前时间是否在允许登录的时间段内
				if (startTime < endTime) {
					// 同一天内的时间段
					this.isLoginAllowed = currentTime >= startTime && currentTime < endTime
				} else {
					// 跨天的时间段（例如22:00-07:00）
					this.isLoginAllowed = currentTime >= startTime || currentTime < endTime
				}

				// 计算下次状态变更时间
				this.calculateNextChangeTime()
			},

			// 计算下次状态变更时间
			calculateNextChangeTime() {
				const now = new Date()
				const currentTime = now.getTime()

				const [startHours, startMinutes, startSeconds] = this.star_time.split(':').map(Number)
				const [endHours, endMinutes, endSeconds] = this.end_time.split(':').map(Number)

				// 创建今天的开始时间和结束时间
				const startToday = new Date()
				startToday.setHours(startHours, startMinutes, startSeconds, 0)

				const endToday = new Date()
				endToday.setHours(endHours, endMinutes, endSeconds, 0)

				// 如果开始时间已经过了，计算明天的开始时间
				const startTomorrow = new Date(startToday)
				startTomorrow.setDate(startTomorrow.getDate() + 1)

				// 如果结束时间已经过了，计算明天的结束时间
				const endTomorrow = new Date(endToday)
				endTomorrow.setDate(endTomorrow.getDate() + 1)

				let nextChangeTime

				if (this.isLoginAllowed) {
					// 当前允许登录，下次变更为禁止登录的时间
					nextChangeTime = endToday > now ? endToday : endTomorrow
				} else {
					// 当前禁止登录，下次变更为允许登录的时间
					nextChangeTime = startToday > now ? startToday : startTomorrow
				}

				// 格式化下次变更时间
				const hours = nextChangeTime.getHours().toString().padStart(2, '0')
				const minutes = nextChangeTime.getMinutes().toString().padStart(2, '0')
				const seconds = nextChangeTime.getSeconds().toString().padStart(2, '0')

				this.nextChangeTime = `${hours}:${minutes}:${seconds}`
			},

			// 启动状态检查定时器
			// startStatusCheckTimer() {
			//   // 每分钟检查一次登录状态
			//   this.timer = setInterval(() => {
			//     this.checkLoginStatus()
			//   }, 60000)
			// },

			// 保存登录时间设置
			async saveLoginTime() {
				if (!this.isValidTimeRange) return

		
				try {
					// 保存设置到本地存储
					const res = await request({
						url: 'index/time-save',
						method: 'post',
						data: {
							star_time: this.star_time,
							end_time: this.end_time
						}
					})
					uni.showToast({
						title: '设置保存成功',
						icon: 'success'
					})

					// 更新登录状态
					this.checkLoginStatus()
				} catch (error) {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					})
				}
			},
			
		}
	}
</script>

<style lang="scss">
	.login-time-container {
		padding: 40rpx 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.header {
		padding: 20rpx 0 40rpx;
		text-align: center;

		.title {
			font-size: 40rpx;
			font-weight: 600;
			color: #333;
		}
	}

	.time-picker {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 20rpx 0;
		margin-bottom: 40rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.picker-item {
			display: flex;
			align-items: center;
			padding: 30rpx;
			border-bottom: 2rpx solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			.item-label {
				width: 220rpx;
				font-size: 32rpx;
				color: #333;
			}

			.picker-value {
				flex: 1;
				text-align: right;
				font-size: 32rpx;
				color: #666;
			}
		}
	}

	.time-range-tip {
		background-color: rgba(56, 194, 126, 0.1);
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;

		text {
			font-size: 30rpx;
			color: #333;
		}

		.time-range {
			color: #38c27e;
			font-weight: 500;
		}
	}

	.time-validation {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 60rpx;

		.warning-icon {
			font-size: 36rpx;
			color: #ff9900;
			margin-right: 10rpx;
		}

		.warning-text {
			font-size: 30rpx;
			color: #ff9900;
		}
	}

	.save-btn {
		width: 100%;
		height: 96rpx;
		line-height: 96rpx;
		background-color: #38c27e;
		color: #fff;
		font-size: 34rpx;
		border-radius: 48rpx;
		margin-bottom: 40rpx;
	}

	.save-btn[disabled] {
		background-color: #e5e5e5;
		color: #999;
	}

	.current-status,
	.next-change {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.status-label,
		.change-label {
			font-size: 30rpx;
			color: #666;
		}

		.status-value,
		.change-time {
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
		}

		.allowed {
			color: #38c27e;
		}

		.blocked {
			color: #ff5757;
		}
	}
</style>